import logging
from django.http import HttpResponse
import os
from django.shortcuts import render
from .models import Movie, Schedule
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from .forms import UserRegistrationForm

logger = logging.getLogger(__name__)

def index(request):
    try:
        logger.info("访问 index 视图")
        return HttpResponse("欢迎访问电影票应用！")
    except Exception as e:
        logger.error(f"index 视图出错: {e}")
        return HttpResponse("视图出错，请稍后重试", status=500)

def favicon(request):
    try:
        logger.info("访问 favicon 视图")
        favicon_path = os.path.join('static', 'favicon.ico')
        if os.path.exists(favicon_path):
            with open(favicon_path, 'rb') as f:
                return HttpResponse(f.read(), content_type='image/x-icon')
        else:
            return HttpResponse(status=404)
    except Exception as e:
        logger.error(f"favicon 视图出错: {e}")
        return HttpResponse("视图出错，请稍后重试", status=500)


def movie_list(request):
    try:
        movies = Movie.objects.all()
        return render(request, 'movie_list.html', {'movies': movies})
    except Exception as e:
        print(f"查询电影列表时出错: {e}")
        return render(request, 'movie_list.html', {'movies': []})

def schedule_list(request, movie_id):
    schedules = Schedule.objects.filter(movie_id=movie_id)
    return render(request, 'schedule_list.html', {'schedules': schedules})


def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('movie_list')
    else:
        form = UserRegistrationForm()
    return render(request, 'register.html', {'form': form})
